package com.hotevent.controller;

import com.hotevent.entity.Comment;
import com.hotevent.entity.Hotevent;
import com.hotevent.service.CommentService;
import com.hotevent.service.HoteventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Date;
import java.util.List;

@Controller
public class HoteventController {

    @Autowired
    HoteventService hoteventService;

    @Autowired
    CommentService commentService;

    //每页行数
    int pageRowsCount = 3;

    @RequestMapping("/index")
    public String index(Model model,
                        @RequestParam(value="keyWord",
                                required = false,
                                defaultValue = "") String keyWord,
                        @RequestParam(value="startPage",
                                    required = false,
                                    defaultValue = "1") int startPage){

        int pageCount = hoteventService.getBykeyWordPageCount(keyWord,pageRowsCount);
        if(startPage<1){
            startPage = 1;
        }else if(startPage > pageCount){
            startPage = pageCount;
        }
        List<Hotevent> hotevents
                = hoteventService.getBykeyWord(keyWord,startPage,pageRowsCount);
        model.addAttribute("hotevents",hotevents);
        model.addAttribute("pageCount",pageCount);
        model.addAttribute("startPage",startPage);
        model.addAttribute("keyWord",keyWord);
        return "index";
    }

    @RequestMapping("/detail/{id}")
    public ModelAndView eventDetail(@PathVariable("id") int id){
        ModelAndView mv = new ModelAndView("detail");
        Hotevent hotevent = hoteventService.getOne(id);
        List<Comment> comments = commentService.getByEventId(id);
        mv.addObject("hotevent",hotevent);
        mv.addObject("comments",comments);
        return mv;
    }

    @RequestMapping("/addComment")
    public String addComment(Comment comment){
        comment.setCommentDate(new Date(System.currentTimeMillis()));
        this.commentService.add(comment);
        return "redirect:detail/"+comment.getHotEventsId();
    }
}
